
package com.vodafone.nowplus.android.peoplemail.singlesignon;

import java.lang.reflect.Field;
import java.security.Key;

import android.content.Intent;

/**
 * Container for user data. The class contains methods for automatically
 * encrypting and decrypting all data and writing it to intents or reading from
 * intents. All fields in this class must be public String because they are
 * handled using reflection
 */
public class UserData {

    // mandatory
    public String userName;

    // mandatory
    public String password;

    // optional
    public String nickName;

    // optional
    public String firstName;

    // optional
    public String lastName;

    // optional
    public String loggedIn;

    /**
     * Writes all public Strings into the intent
     * 
     * @param intent Intent to be written into
     * @throws IllegalAccessException
     */
    public void writeToIntent(Intent intent) throws IllegalAccessException {
        Field fields[] = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            intent.putExtra(field.getName(), (String)field.get(this));

        }
    }

    /**
     * Reads all public Strings from intent
     * 
     * @param intent Intent to be read from
     * @throws Exception
     */
    public void readFromIntent(Intent intent) throws Exception {
        Field fields[] = this.getClass().getDeclaredFields();
        for (Field field : fields) {

            field.set(this, intent.getStringExtra(field.getName()));

        }
    }
    

    /**
     * Encrypts all public fields
     * 
     * @param key PublicKey for encryption
     * @throws Exception
     */
    public void enCryptUserData(Key key) throws Exception {
        RSACrypter crypter = new RSACrypter();
        Field fields[] = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            
                field.set(this,crypter.enCrypt((String)field.get(this),key));
            
        }

    }

    /**
     * Decrypts all public fields
     * 
     * @param key PrivateKey for decryption
     * @throws Exception
     */
    public void deCryptUserData(Key key) throws Exception {
        RSACrypter crypter = new RSACrypter();
        Field fields[] = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            
                field.set(this,crypter.deCrypt((String)field.get(this),key));
            
        }
        
    }
    
}
